package com.ckzp.weixin;

import com.ckzp.core.json.Jmode;
import com.ckzp.core.json.JsonUtil;
import com.ckzp.core.util.StringUtil;
import com.ckzp.jfinal.system.model.Demo;
import com.ckzp.plugins.layui.LayuiData;
import com.jfinal.kit.HttpKit;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by 51594 on 2023/4/7.
 */
public class MediaTool {

    public static String MEDIA_COUNT_URL = "https://api.weixin.qq.com/cgi-bin/material/get_materialcount?access_token=";
    public static String MEDIA_LIST_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=";
    //上传接口
    public static String MEDIA_UPLOAD_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&type=TYPE";
    // public static String MEDIA_UPLOAD_URL = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";


    /**
     * 上传接口
     *
     * @return
     */
    public static String getMediaUploadUrl() {
        return MEDIA_UPLOAD_URL + AccessTokenTool.getAccessToken();
    }

    /**
     * 获取素材总数
     * 1.永久素材的总数，也会计算公众平台官网素材管理中的素材
     * 2.图片和图文消息素材（包括单图文和多图文）的总数上限为100000，其他素材的总数上限为1000
     * 3.调用该接口需https协议
     * https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_the_total_of_all_materials.html
     */
    public static Jmode getMediaCount() {
        String result = HttpKit.get(MEDIA_COUNT_URL + AccessTokenTool.getAccessToken());
        Map m = JsonUtil.toObject(result, Map.class);
        if (m != null) {
            return Jmode.n().set("code", 0)
                    .set("voice_count", StringUtil.getInt(m, "voice_count"))
                    .set("video_count", StringUtil.getInt(m, "video_count"))
                    .set("image_count", StringUtil.getInt(m, "image_count"))
                    .set("news_count", StringUtil.getInt(m, "news_count"));
        }
        return Jmode.n().set("code", 9);
    }


    /**
     * 在新增了永久素材后，开发者可以分类型获取永久素材的列表。
     * 1、获取永久素材的列表，也包含公众号在公众平台官网素材管理模块中新建的图文消息、语音、视频等素材
     * 2、临时素材无法通过本接口获取
     * 3、调用该接口需https协议
     * https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_materials_list.html
     *
     * @param type
     * @param pageid
     * @param pagesize
     * @return
     */
    public static LayuiData getMediaList(String type, int pageid, int pagesize) {
        if (pageid < 1) pageid = 1;
        int offset = (pageid - 1) * pagesize;
        String result = HttpKit.post(MEDIA_LIST_URL + AccessTokenTool.getAccessToken(),
                Jmode.n().set("type", type).set("offset", offset).set("count", pagesize).toJson());
        Map m = JsonUtil.toObject(result, Map.class);
        int errcode = StringUtil.getInt(m, "errcode");
        if (errcode > 0) {
            return LayuiData.n().setCode(errcode).setMsg(StringUtil.getString(m, "errmsg"));
        } else {
            return LayuiData.n().setCount(StringUtil.getInt(m, "total_count")).setData((List) m.get("item"));
        }
    }


    /**
     * 上传多媒体数据到微信服务器
     *
     * @param mediaFileUrl 来自网络上面的媒体文件地址
     * @return
     */
    public static String uploadMedia(String type, String mediaFileUrl) {
        StringBuffer resultStr = null;
        //拼装url地址
        String mediaStr = MEDIA_UPLOAD_URL.replace("ACCESS_TOKEN", AccessTokenTool.getAccessToken()).replace("TYPE", type);
        System.out.println("mediaStr:" + mediaStr);
        URL mediaUrl;
        InputStream in = null;
        BufferedInputStream bufferedIn = null;
        InputStream resultIn = null;
        InputStreamReader reader = null;
        BufferedReader bufferedReader = null;
        try {
            String boundary = "----WebKitFormBoundaryOYXo8heIv9pgpGjT";
            URL url = new URL(mediaStr);
            HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
            //让输入输出流开启
            urlConn.setDoInput(true);
            urlConn.setDoOutput(true);
            //使用post方式请求的时候必须关闭缓存
            urlConn.setUseCaches(false);
            //设置请求头的Content-Type属性
            urlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            urlConn.setRequestMethod("POST");
            //获取输出流，使用输出流拼接请求体
            OutputStream out = urlConn.getOutputStream();

            //读取文件的数据,构建一个GET请求，然后读取指定地址中的数据
            mediaUrl = new URL(mediaFileUrl);
            HttpURLConnection mediaConn = (HttpURLConnection) mediaUrl.openConnection();
            //设置请求方式
            mediaConn.setRequestMethod("GET");
            //设置可以打开输入流
            mediaConn.setDoInput(true);
            //获取传输的数据类型
            String contentType = mediaConn.getHeaderField("Content-Type");
            //将获取大到的类型转换成扩展名
            String fileExt = judgeType(contentType);
            //获取输入流，从mediaURL里面读取数据
            in = mediaConn.getInputStream();
            bufferedIn = new BufferedInputStream(in);
            //数据读取到这个数组里面
            byte[] bytes = new byte[1024];
            int size = 0;
            //使用outputStream流输出信息到请求体当中去
            out.write(("--" + boundary + "\r\n").getBytes());
            out.write(("Content-Disposition: form-data; name=\"media\";\r\n"
                    + "filename=\"" + (new Date().getTime()) + fileExt + "\"\r\n"
                    + "Content-Type: " + contentType + "\r\n\r\n").getBytes());
            while ((size = bufferedIn.read(bytes)) != -1) {
                out.write(bytes, 0, size);
            }
            //切记，这里的换行符不能少，否则将会报41005错误
            out.write(("\r\n--" + boundary + "--\r\n").getBytes());

            bufferedIn.close();
            in.close();
            mediaConn.disconnect();

            resultIn = urlConn.getInputStream();
            reader = new InputStreamReader(resultIn);
            bufferedReader = new BufferedReader(reader);
            String tempStr = null;
            resultStr = new StringBuffer();
            while ((tempStr = bufferedReader.readLine()) != null) {
                resultStr.append(tempStr);
            }
            bufferedReader.close();
            reader.close();
            resultIn.close();
            urlConn.disconnect();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) in.close();
                if (bufferedIn != null) bufferedIn.close();
                if (resultIn != null) resultIn.close();
                if (reader != null) reader.close();
                if (bufferedReader != null) bufferedReader.close();
            } catch (Exception e) {

            }
        }

        return resultStr.toString();
    }

    /**
     * 通过传过来的contentType判断是哪一种类型
     *
     * @param contentType 获取来自连接的contentType
     * @return
     */
    public static String judgeType(String contentType) {
        String fileExt = "";
        System.out.println(contentType);
        if ("image/jpeg".equals(contentType)) {
            fileExt = ".jpg";
        } else if ("image/png".equals(contentType)) {
            fileExt = ".png";
        } else if ("audio/mpeg".equals(contentType)) {
            fileExt = ".mp3";
        } else if ("audio/amr".equals(contentType)) {
            fileExt = ".amr";
        } else if ("video/mp4".equals(contentType)) {
            fileExt = ".mp4";
        } else if ("video/mpeg4".equals(contentType)) {
            fileExt = ".mp4";
        }
        return fileExt;
    }
}
